import {
  getMenuListApi,
  createMenuApi,
  updateMenuApi,
  deleteMenuApi,
} from "@/api/menu";
import { ref } from "vue";
import { defineStore } from "pinia";
import menuArranagement from "@/utils/menuArranagement";
import { ElMessage } from "element-plus";

export const useMenuStore = defineStore(
  "menu",
  () => {
    const menuList = ref([]);

    async function getMenuList() {
      const res = await getMenuListApi();
      if (res.data.code === 200) {
        menuList.value = menuArranagement(res.data.data);
        return true;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("获取菜单失败");
        return false;
      }
    }

    async function createMenu(data) {
      const res = await createMenuApi(data);
      if (res.data.code === 200) {
        return await getMenuList();
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("创建菜单失败");
        return false;
      }
    }

    async function updateMenu(data) {
      const res = await updateMenuApi(data);
      if (res.data.code === 200) {
        return await getMenuList();
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("更新菜单失败");
        return false;
      }
    }

    async function deleteMenu(id) {
      const res = await deleteMenuApi(id);
      if (res.data.code === 200) {
        return await getMenuList();
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("删除菜单失败");
        return false;
      }
    }

    return {
      menuList,
      getMenuList,
      createMenu,
      updateMenu,
      deleteMenu,
    };
  },
  {
    persist: {
      storage: sessionStorage,
      paths: ["menuList"],
    },
  }
);

export function useMenuStoreHook() {
  const menuStore = useMenuStore();
  return menuStore;
}
